<!--
 * @Descripttion: 
 * @version: 
 * @Author: weni09
 * @Date: 2021-04-19 14:07:40
 * @LastEditors: weni09
 * @LastEditTime: 2021-06-17 10:36:41
 * @FilePath: \icoder-frontend\blog\src\views\Home.vue
-->

<template>
	<div class="home">
		<el-row id="artList" type="flex" :gutter="50" justify="center">
			<el-col :span="12">
				<el-row class="search-desc" v-if="hideSlogan">
					<el-card shadow="hover" class="search-result-card">
					<p class="search-tag">{{$t('home.total')}} {{ articleResListFCount }} {{ $t('home.piece') }}</p>
                    <h4>
						<strong>{{ searchTitle }}："{{resNameF}}" {{$t('article.relatedArticles')}}</strong>
					</h4>
					</el-card>
				</el-row>
				<el-row class="art-item" :class="{'search':hideSlogan}">
					<template v-if="!hideSlogan">
						<art-card v-for="article in articleList" :key="article.id" :article="article" ></art-card>
					</template>
					<template v-else-if="hideSlogan">
						<art-card v-for="article in articleResListFData" :key="article.id" :article="article" ></art-card>
					</template>
				</el-row>
				<div class="more">
					<el-button
					type="text"
					:loading="loading"
					class="load-more more-btn"
					@click="loadMore"
					:disabled="moreBtnDisabled"
					round>{{ getMoreText }}</el-button>
				</div>
			</el-col>
			<el-col :span="5" class="hidden-sm-and-down">
			<div class="item category">
				<category
				@getResNameF="getResNameF"
				@getArticleByResF="getArticleByResF"></category>
			</div>
			<div class="item tag">
				<tag 
				 @getResNameF="getResNameF"
				 @getArticleByResF="getArticleByResF"></tag>
			</div>
			<!-- <div class="item friend">
				<friend></friend>
			</div> -->
			
			<el-backtop class="backtop"  :bottom="100" :right="200" :visibility-height="100">
				<span class="iconfont icon-backtop"></span>
  			</el-backtop>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	import friend from 'components/Friend';
	import tag from 'components/Tag';
	import category from 'components/Category';
	import ArticleCard from 'components/ArticleCard';
	import { fetchArticleList } from 'api';
	import { mapActions } from 'vuex';
	export default {
		name: 'home',
		components: {
			friend,
			tag,
			category,
			"art-card":ArticleCard,
		},
		data() {
			return{
				articleList:[],
				tempArticleList:[],
				resNameF:'',
				articleResListFData:[],
				articleResListFCount:0,
				offset:0,
				limit:10,
				count:0,
				// hasNextPage: true,
				moreBtnDisabled:false,
				loading:false,
				
			}
		},
		inject:['reload'],
		methods:{
		...mapActions(['setHasNextPage']),
		getArticleList(){
			let params={
				offset: this.offset,
            	limit: this.limit,
				sort: '-create_date'
			}
            fetchArticleList(params).then(res => {
                this.articleList = res.data || []
				if (this.articleList.length < 10){
					this.setHasNextPage(false)
				}
                }).catch(err => {
                    console.log(err)
                });
        },
		getResNameF: function(resName){
			this.resNameF = resName
			this.initCountTempData();//点击标签/分类后，初始化计数和临时数组
			this.offset = 0;//初始化偏移量
		},
		getArticleByResF: function(articleResData){
			this.articleResListFData = articleResData.data
			this.articleResListFCount = articleResData.total
		},
		initCountTempData:function(){
			this.count = 0;
			this.tempArticleList=[];
		},
		renderMore:function(){
			const temp = this.tempArticleList.slice(this.count,this.count+2);
			// console.log(this.count+' ',temp,typeof(temp));
			for (let i in temp){
				// console.log('item '+i,temp[i],typeof(temp[i]));
				if (temp[i]){
					if (!this.$route.params.slug){
						this.articleList.push(temp[i]);
					}
					else{
						this.articleResListFData.push(temp[i]);
						// console.log(this.articleResListFData)
						this.articleResListFCount = this.articleResListFData.length;
					}
				}
			}
			// console.log(this.articleList)
			this.count += 2;
			this.offset += 2;
			//计数不等于10时，临时数组的长度小于等于计数时，关闭下一页
			if (this.count !=10 && this.tempArticleList.length <= this.count ){
				this.setHasNextPage(false)
			}
			//计数等于10时，初始化计数和临时数组
			// console.log(this.count,this.offset)
			if (this.count == 10){
				this.initCountTempData()
			}
          	this.loading = false
        },
		getParamsForload:function(){
			let params = {}
			if (this.$route.params.slug){
				params = {
				res:this.$route.params.res,
				slug: this.$route.params.slug,
            	offset: this.offset + 10,
            	limit: this.limit,
				sort: '-create_date'
				};
			}
			else{
				params = {
            	offset: this.offset + 10,
            	limit: this.limit,
				sort: '-create_date'
			};
			}
			return params
		},
		loadMore() {
			this.loading = true
			if (this.offset % 10 == 0){
				// console.log("is or not request"+this.offset);
				let params = this.getParamsForload();
				this.tempArticleList = [];
            	fetchArticleList(params).then(res => {
					// console.log(res.data,typeof(res.data))
                	this.tempArticleList = res.data || []
					if (this.tempArticleList){
						setTimeout(this.renderMore,500)
					}
					else{
						this.setHasNextPage(false)
					}
                	}).catch(err => {
                    console.log(err)
                });
				
			}
			else{
				setTimeout(this.renderMore,500)
			}
			
            },
			//Home,创建时初始化数据
			initState:function(){
			if (!this.hideSlogan){
				this.setHasNextPage(true);//home创建时，初始化hasNextPage为true
				// console.log("is or not this.hideSlogan",this.hideSlogan)
				this.getArticleList();
			}
			},
		},

		watch:{
		},
		computed:{
            hideSlogan() {
                return this.$route.params.slug
            },
			getMoreText:function(){
				if (this.$store.getters.hasNextPage){
				this.moreBtnDisabled=false
				var moreStr = this.$t('home.more')
				var loadingStr= this.$t('home.loading')
					if (this.loading){
						return loadingStr
					}
					else{
						return moreStr
					}
				}
				else{
					this.moreBtnDisabled=true
					return this.$t('home.noMore')
				}
			},
			searchTitle:function(){
				const temp = this.$route.params.res + '.name'
				return this.$t(temp)
			}
		},
		
		mounted(){
			this.initState();
		},
		created(){
		
		},
	}
</script>

<style lang="scss" scoped>
.side-img {
    height: 150px;
    width: 270px;
    overflow: hidden;
    margin-right: 10px;
}
</style>